<?php

class CabController extends Zend_Controller_Action {

    const NEW_MODULE_BASE_URL = "http://chatvl.com/new";  //1,2
    const HOT_MODULE_BASE_URL = "http://chatvl.com/hot"; //1.2 module anh moi
    const MYTH_MODULE_BASE_URL = "http://chatvl.com/vote"; //hai vo doi
    
    const BASE_URL = "http://chatvl.com/";
    const COLLECTION_MODULE_BASE_URL = "http://chatvl.com/";    

    private static $query_cache;
    private static $memcache;

    public function __construct(\Zend_Controller_Request_Abstract $request, \Zend_Controller_Response_Abstract $response, array $invokeArgs = array()) {
        parent::__construct($request, $response, $invokeArgs);

    }
    
    public function testfileAction(){
         $this->_helper->viewRenderer->setNoRender(true);
         
        $frontendoptions = array(
            'lifetime' => 60 * 0, // 15minutes
            'automatic_serialization' => true
        );
        $backendoptions = array(
            'cache_dir' => sys_get_temp_dir(),
            'file_name_prefix' => 'zend_cache_query_cabMeme',
            'hashed_directory_level' => 2
        );
        self::$query_cache = Zend_Cache::factory('Core', 'File', $frontendoptions, $backendoptions);
    }
    
    public function testmemAction(){
         $this->_helper->viewRenderer->setNoRender(true);
         self::$memcache = new Memcache;
         self::$memcache->connect(Haibl_ConfigData::DOMAIN, Haibl_ConfigData::PORT) or die("Could not connect");
    }

    public function getAccessMemcachedKey() {
        $params = $this->_request->getParams();
        $requestParams = '';
        foreach ($params as $key => $value) {
            if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                $requestParams.= $key . '=' . $value;
            }
        }
        $action = $this->_request->getActionName();
        return md5($action . $requestParams);
    }

    public function checkAccessKeyParams() {
        $page = $this->_request->getParam("page");
        $appid = $this->_request->getParam("key");
        $sig = $this->_request->getParam("sig");
        $method = $this->_request->getParam("method");
        $db = $this->_request->getParam("db");
        if($db == '1'){
            return true;
        }
        if ($appid == "" || $sig == "" || $page == "" || $method == "") {
            echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$INVAILD_PARAMS);
            return false;
        } else {
            if ($appid != Haibl_ConfigData::KEY) {
                echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                return false;
            } else {
                $params = $this->_request->getParams();
                $requestParams = '';
                foreach ($params as $key => $value) {
                    if ($key != 'controller' && $key != 'action' && $key != 'module' && $key != "sig") {
                        $requestParams.= $key . '=' . $value;
                    }
                }
                $requestParams.= Haibl_ConfigData::ACCESS_KEY;
                $encryptParams = md5($requestParams);

                if ($encryptParams == $sig) {
                    return true;
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$NOT_FOUND_APIKEY);
                    if (Haibl_ConfigData::DEBUG) {
                        echo "<p>encryptParams = " . $encryptParams . "</p>";
                    }
                    return false;
                }
            }
        }
    }

    public function indexAction() {
        $this->_helper->viewRenderer->setNoRender(true);
        $isAccess = $this->checkAccessKeyParams();
        if ($isAccess) {

            $method = $this->_request->getParam("method") == "" ? "new" : $this->_request->getParam("method");
            $page = $this->_request->getParam("page") == "" ? 1 : $this->_request->getParam("page");

            $key = $this->getAccessMemcachedKey();
            $memCachedData = null;
            if ($memCachedData != null) {
                echo json_encode($memCachedData);
            } else {
                $lists = null;
                if ($method == "new") {
                    $lists = $this->getImageLists(static::NEW_MODULE_BASE_URL ."/". $page);
                } else if ($method == "hot") {
                    $lists = $this->getImageLists(static::HOT_MODULE_BASE_URL ."/". $page);
                } else if ($method == "myth") {
                    $lists = $this->getImageLists(static::MYTH_MODULE_BASE_URL ."/". $page);
                } else if ($method == "suutam") {
                    $lists = $this->getImageLists(static::COLLECTION_MODULE_BASE_URL ."/". $page);
                }

                $returnData = array();
                if ($lists != null && !empty($lists)) {
                    $returnData['errorId'] = Sunny_ErrorHandled::$DONE;
                    $returnData['data'] = $lists;
                    echo json_encode($returnData);
                } else {
                    echo Sunny_ErrorHandled::handleError(Sunny_ErrorHandled::$PAGE_NOT_FOUND);
                }
            }
        }
    }

    public function clearAction() {

        $this->_helper->viewRenderer->setNoRender(true);
        echo "clear";
        self::$query_cache->clean(Zend_Cache::CLEANING_MODE_ALL);
        echo "clear";
    }

    function getImageLists($baseUrl) {
        $key = $this->getAccessMemcachedKey();
        if (true) {
            $client = new Zend_Http_Client();
            $client->setUri($baseUrl);
            $response = $client->request();
            $html = $response->getBody();
            $dom = new Zend_Dom_Query($html);
            $results = $dom->query('.gag-link');

            $data = array();
            $dataIndex = 0;

            $results->rewind();
            while ($results->valid()) {                
                
                $domDoc = $results->current();

                if ($domDoc->getAttribute('class') == ' gag-link') {
                    $data[$dataIndex]['img'] = $domDoc->getAttribute('data-url');
                    $data[$dataIndex]['title'] = $domDoc->getAttribute('data-text');                    

                    $img = $domDoc->getElementsByTagName("img")->item(0);
                    if ($img != null) {

                        $data[$dataIndex]['src'] = $img->getAttribute('src');

                        $imgLink = trim($data[$dataIndex]['src']);

                        if ($imgLink == '') {
                            $data[$dataIndex]['src'] = 'http://img.youtube.com/vi/Xv8_ImS5lVE0/0.jpg';
                        }

                        $data[$dataIndex]['video'] = "0";
                        $imgVideoIndicator = $domDoc->getElementsByTagName("img")->item(1);
                        if(isset($imgVideoIndicator)){                            
                            if($imgVideoIndicator->getAttribute('class') == 'videoIndicator'){
                                $data[$dataIndex]['video'] = "1";
                                
                                $imgLink = $data[$dataIndex]['src'];
                                $id = '';
                                if (strpos($imgLink, 'vi/')) {
                                    $rs = explode('vi/', $imgLink);
                                    $rs = explode('&', $rs[1]);
                                    $id = $rs[0];
                                    $rs = explode('/', $id);
                                    $imgLink = $rs[0];
                                    
                                    $data[$dataIndex]['videoLink'] = 'http://www.youtube.com/embed/' . $imgLink;
                                }                                
                            }
                        }
                    }

                    $a = $domDoc->getElementsByTagName("a");
                    for ($i = 0; $i < $a->length; $i++) {
                        $aCurrent = $a->item($i);
                        if (strpos($aCurrent->getAttribute('href'), "user")) {
                            $data[$dataIndex]['uploader'] = $aCurrent->nodeValue;
                            break;
                        }
                    }

                    $span = $domDoc->getElementsByTagName("span");
                    for ($i = 0; $i < $span->length; $i++) {
                        $spanCurrent = $span->item($i);
                        if ($spanCurrent->getAttribute('class') == 'comment') {
                            $data[$dataIndex]['comment'] = trim($spanCurrent->nodeValue);
                        }
                        if ($spanCurrent->getAttribute('class') == 'viewed') {
                            $data[$dataIndex]['viewed'] = trim($spanCurrent->nodeValue);
                            break;
                        }
                    }
                    $dataIndex++;
                }
                $results->next();
            }
            
            
//            self::$query_cache->save($data, $key);
            return $data;
        } else {
            return $result;
        }
    }

}
?>

